package com.oneclick.tools.applock.db;

import java.util.ArrayList;

import com.oneclick.tools.applock.bean.PackageInfo;
import com.oneclick.tools.applock.utils.Constant;
import com.oneclick.tools.applock.utils.Log;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class PackageContentProvider {
	
	private Context context;
	private SQLiteOpenHelper sqLiteOpenHelper;

	public PackageContentProvider(Context context) {
		super();
		this.context = context;
		sqLiteOpenHelper = new DBHelper(context);
	}
	
	public int delete(long id) {
		SQLiteDatabase database = sqLiteOpenHelper.getWritableDatabase();
		
		int affected = database.delete("t_package", "_id=?", new String[]{ String.valueOf(id) });
		
		database.close();
		return affected;
	}
	
	public long save(PackageInfo packageInfo) {
		SQLiteDatabase database = sqLiteOpenHelper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put("package_name", packageInfo.getPackageName());
		values.put("label", packageInfo.getLabel());
		
		long id = database.insert("t_package", "", values);
		Log.i("save one package:" + packageInfo.getPackageName());
		database.close();
		return id;
	}
	
	public ArrayList<PackageInfo> queryPackages() {
		SQLiteDatabase database = sqLiteOpenHelper.getReadableDatabase();
		ArrayList<PackageInfo> packageInfos = new ArrayList<PackageInfo>();
		
		Cursor cursor = database.query("t_package", null, null, null, null, null, null);
		
		while(cursor.moveToNext()) {
			
			int id = cursor.getInt(cursor.getColumnIndex("_id"));
			String packageName = cursor.getString(cursor.getColumnIndex("package_name"));
			String label = cursor.getString(cursor.getColumnIndex("label"));
			
			PackageInfo packageInfo = new PackageInfo(id, label, packageName);
			packageInfos.add(packageInfo);
		}
		
		cursor.close();
		database.close();
		
		return packageInfos;
	}
	
	private class DBHelper extends SQLiteOpenHelper {

		public DBHelper(Context context) {
			super(context, Constant.DB_NAME, null, Constant.DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE IF NOT EXISTS t_package (" + 
						"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
						"package_name TEXT," +
						"label TEXT" +
						");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			/*
			 * Do nothing
			 */
		}
	}
}
